export default {
  namespaced: true,
  state: {
    // 存放 商品数组
    goodList: uni.getStorageSync('cart') || []
  },
  mutations: {
    // 加入商品导购物车
    setGoodList (state, good) {
      // 判断，当前点击的数据 是否已经存在 goodList，存在的话 直接添加当前商品数量，否则添加新商品到 goodList
      const index = state.goodList.findIndex(item => item.goods_id === good.goods_id)
      if (index > -1) {
        state.goodList[index].count++
      } else {
        state.goodList.push(good)
      }
      // console.log(state.goodList)
      uni.setStorageSync('cart', state.goodList)
    },
    // 修改 购物车选中状态
    changeChecked (state, { id }) {
      state.goodList = state.goodList.map(item => {
        if (item.goods_id === id) {
          item.checked = !item.checked
          return item
        }
        return item
      })
      uni.setStorageSync('cart', state.goodList)
    },
    // 全选改变单选
    changeAll (state, { checkedAll }) {
      // console.log(checkedAll)
      state.goodList = state.goodList.map(item => {
        item.checked = checkedAll
        // console.log(item.checked)
        return item
      })
      uni.setStorageSync('cart', state.goodList)
    },
    // 计算商品的数量
    changeGoodsCount (state, { id, unit }) {
      state.goodList = state.goodList.map(item => {
        if (item.goods_id === id) {
          item.count = item.count + unit
          return item
        }
        return item
      })
      uni.setStorageSync('cart', state.goodList)
    },
    delGoods (state, id) {
      state.goodList = state.goodList.filter(item => item.goods_id !== id)
      uni.setStorageSync('cart', state.goodList)
    },
    changeShow (state, id) {
      state.goodList = state.goodList.map(item => {
        if (item.goods_id === id) {
          item.show = true
          return item
        }
        return item
      })
      uni.setStorageSync('cart', state.goodList)
    },
    closeCartGoodShow (state) {
      state.goodList = state.goodList.map(item => {
        item.show = false
        return item
      })
    }
  },
  getters: {
    // 商品总数
    goodsTotal (state) {
      let sum = 0
      state.goodList.forEach((goods) => (sum += goods.count))
      return sum
    },
    // 全选状态
    checkedAll (state) {

      return state.goodList.length ? state.goodList.every(item => item.checked) : false
    },
    // 选中商品列表
    checkedList (state) {
      return state.goodList.filter(item => item.checked)
    },
    // 商品总价
    goodsTotalPrice (state, getters) {
      return getters.checkedList.reduce((total, item) => {
        return total += item.goods_price * item.count
      }, 0)
    }
  },
  actions: {
    setGoodListAPI () {

    }
  }
}